﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace NPOI基础
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (FileStream stream = new FileStream(@"C:\1.xls", FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = new HSSFWorkbook(stream);
                //MessageBox.Show(workbook.GetSheetName(0));
                ISheet sheet = workbook.GetSheet("Test1");
                IRow row = sheet.GetRow(0);
                List<ICell> list = row.Cells;
                foreach (ICell cell in list)
                {
                    MessageBox.Show(cell.ToString());
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            using (FileStream stream = new FileStream(@"C:\1.xls", FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = new HSSFWorkbook(stream);
                ISheet sheet = workbook.GetSheetAt(0);
                IRow row = sheet.GetRow(1);
                string value =  row.GetCell(0).StringCellValue;
                MessageBox.Show(value);

                IRow row2 = sheet.GetRow(0);
                double value2 = row2.GetCell(0).NumericCellValue;
                MessageBox.Show(value2.ToString());
                
                int rowNum = sheet.LastRowNum;
                MessageBox.Show(rowNum.ToString());
            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            HSSFWorkbook wb = new HSSFWorkbook();
            ISheet sheet =  wb.CreateSheet("Test");
            IRow row = sheet.CreateRow(0);
            ICell cell = row.CreateCell(0, CellType.STRING);
            cell.SetCellValue("Hello World");
            IRow row2 = sheet.CreateRow(1);
            ICell cell2 = row2.CreateCell(2, CellType.NUMERIC);
            cell2.SetCellValue(2013);
            using (FileStream stream = new FileStream(@"C:\2.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                wb.Write(stream);
            }
        }
    }
}
